package cn.suxiaoxiang.suwebverify.command;

import cn.suxiaoxiang.suwebverify.SuWebVerify;
import cn.suxiaoxiang.suwebverify.config.MessageConfig;
import cn.suxiaoxiang.suwebverify.util.PasswordUtil;
import cn.suxiaoxiang.suwebverify.util.SQLiteManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * setPassWordCommand - 重新设置用户密码
 *
 * @author 程序员-Su_xiaoxiang
 * @date 2025/5/11 16:42
 */
public class SetPasswordCommand implements CommandExecutor, TabExecutor, Listener {
    private final SuWebVerify plugin;
    private final MessageConfig messageConfig;
    private final String prefix;

    public SetPasswordCommand(SuWebVerify plugin) {
        this.plugin = plugin;
        this.messageConfig = new MessageConfig(plugin);
        this.messageConfig.loadPlayerCommandConfig();
        this.prefix = plugin.getConfig().getString("prefix");
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!sender.hasPermission("suwebverify.setpassword")) {
            sender.sendMessage(ChatColor.RED + prefix + "你没有权限设置玩家密码！");
            return false;
        }

        if (args.length != 2) {
            sender.sendMessage(ChatColor.RED + prefix + "用法: /swv setpassword <玩家名> <新密码>");
            return false;
        }

        String targetPlayer = args[0];
        String newPassword = args[1];

        // 检查目标玩家是否存在
        if (!isPlayerExists(targetPlayer)) {
            sender.sendMessage(ChatColor.RED + prefix + "玩家 " + targetPlayer + " 不存在！");
            return false;
        }

        // 使用 BCrypt 加密新密码
        String encryptedPassword = PasswordUtil.encryptPassword(newPassword);
        if (encryptedPassword == null) {
            sender.sendMessage(ChatColor.RED + prefix + "密码加密失败！");
            return false;
        }

        // 更新数据库中的密码
        if (updatePlayerPassword(targetPlayer, encryptedPassword)) {
            sender.sendMessage(ChatColor.GREEN + prefix + "成功设置玩家 " + targetPlayer + " 的密码！");
            
            // 如果玩家在线，发送通知
            Player player = Bukkit.getPlayer(targetPlayer);
            if (player != null && player.isOnline()) {
                player.sendMessage(ChatColor.YELLOW + prefix + "你的密码已被管理员修改！");
            }
            return true;
        } else {
            sender.sendMessage(ChatColor.RED + prefix + "设置密码失败！");
            return false;
        }
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        List<String> completions = new ArrayList<>();

        if (args.length == 2) {
            // 返回所有在线玩家的名字
            for (Player player : Bukkit.getOnlinePlayers()) {
                completions.add(player.getName());
            }
        }

        return completions;
    }

    /**
     * 判断玩家存在
     *
     * @param username 用户名
     * @return boolean
     */
    private boolean isPlayerExists(String username) {
        String sql = "SELECT * FROM player WHERE username = ?";
        try (PreparedStatement pstmt = SQLiteManager.getConnection().prepareStatement(sql)) {
            pstmt.setString(1, username);
            return pstmt.executeQuery().next();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新玩家密码
     *
     * @param username          用户名
     * @param encryptedPassword 加密密码
     * @return boolean
     */
    private boolean updatePlayerPassword(String username, String encryptedPassword) {
        String sql = "UPDATE player SET password = ? WHERE username = ?";
        try (PreparedStatement pstmt = SQLiteManager.getConnection().prepareStatement(sql)) {
            pstmt.setString(1, encryptedPassword);
            pstmt.setString(2, username);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
